import util from '@/libs/util';
import Cookies from 'js-cookie';
import axios from 'axios';
import CONSTANTS from '../../config/constants.js';

export default {
    data () {
        return {
            columns: [{
                title: '订单号',
                key: 'billcode',
            }, {
                title: '学生姓名',
                key: 'student_name'
            }, {
                title: '实收/退费金额',
                key: 'realAmt_refundAmt',
                render:(h,params)=>{
                    let realAmt=params.row.real_amt;
                    let refundAmt = params.row.refund_amt;
                    return h('span',{},realAmt+"元/"+refundAmt+"元");
                }
            }, {
                title: '打折金额',
                key: 'discount_amt'
            }, {
                title: '班级名称',
                key: 'class_name'
            }, {
                title: '操作员',
                key: 'update_by'
            }, {
                title: '操作时间',
                    key: 'update_time',
                render: (h, params) => {
                    return h('span', {}, util.getDate(params.row.update_time, 'time'));
                }
            }, {
                title: '订单状态',
                key: 'status',
                render: (h, params) => {
                    let text = '';
                    if (params.row.status === 1) text = '待缴费';
                    if (params.row.status === 2) text = '已缴费';
                    if (params.row.status === 3) text = '申请退款';
                    if (params.row.status === 4) text = '已退款';
                    if (params.row.status === 5) text = '已失效';
                    return h('span', {}, text);
                }
            }, {
                title: '操作',
                render: (h, params) => {
                    if (params.row.status === 2) {
                        return h('span', [
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: () => {
                                        this.billId = params.row.id;
                                        this.chargeDetailVisable = true;
                                        this.getOrderDetails();
                                    }
                                }
                            }, '查看'),
                            h('Button', {
                                props: {
                                    type: 'error',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: () => {
                                        this.billId = params.row.id;
                                        this.showRefund(params.row.id);
                                        this.chargeRefundVisable = true;
                                        this.charge_dataList = [];
                                    }
                                }
                            }, '退费'),
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px',
                                    display: params.row.invoicePath ? 'none' : 'inline'
                                },
                                on: {
                                    click: () => {
                                        util.ajax.post('/busine/bill/getPayShit', util.toFormData({// 查询订单详情
                                            billId: params.row.id
                                        })).then(res => {
                                            this.$router.push({
                                                path: 'test',
                                                name: 'test',
                                                params: {
                                                    data: res.data.data,
                                                    entry: 1// 入口
                                                }
                                            });
                                        });
                                    }
                                }
                            }, '生成发票'),
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px',
                                    display: params.row.invoicePath ? 'inline' : 'none'
                                },
                                on: {
                                    click: () => {
                                        util.ajax.post('/busine/bill/getPayShit', util.toFormData({// 查询打印数据
                                            billId: params.row.id
                                        })).then(res => {
                                            this.$router.push({
                                                path: 'test',
                                                name: 'test',
                                                params: {
                                                    data: res.data.data,
                                                    entry: 1// 入口
                                                }
                                            });
                                        });
                                    }
                                }
                            }, '查看发票')
                        ]);
                    } else {
                        return h('span', [
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: () => {
                                        this.billId = params.row.id;
                                        this.chargeDetailVisable = true;
                                        this.getOrderDetails();
                                    }
                                }
                            }, '查看')
                        ]);
                    }
                }
            }],
            total: 0,
            pageSize: 10,
            pageIndex: 1,
            dataList: [],
            queryData: {
                billCode: '',
                studentName: '',
                parentPhone: '',
                className: '',
                status: '',
                areaId: '',
                classYear: '',
                classSeason: ''
            },
            chargeDetailVisable: false,
            chargeRefundVisable: false,
            charge_columns_1: [{
                title: '项目名称',
                key: 'name'
            }, {
                title: '金额(元)',
                key: 'amt'
            }, {
                title: '退费金额(元)',
                key: 'refundAmt'
            }, {
                title: '打折理由'
            }],
            charge_columns_2: [
                {
                    title: '项目名称',
                    key: 'name'
                }, {
                    title: '金额(元)',
                    key: 'amt'
                }, {
                    title: '应收金额',
                    key: 'realAmt'
                }, {
                    title: '已打折金额',
                    key: 'discountedAmt'
                }, {
                    title: '退费金额',
                    key: 'refundAmt',
                    render: (h, params) => {
                        return h('Input', {
                            props: {
                                value: params.row.refundAmt,
                                number: true
                            },
                            on: {
                                'on-blur': (event) => {
                                    let refundAmt = event.target.value;
                                    if (isNaN(refundAmt)) {
                                        this.$Message.warning('请输入正确的数字！');
                                        this.refundFlag=true;
                                        return;
                                    }
                                    if(refundAmt<=0){
                                        this.$Message.warning('退款不能为0！');
                                        this.refundFlag=true;
                                        return;
                                    }
                                    let realAmt = this.charge_dataList[params.index].realAmt;
                                    if (refundAmt > realAmt) {
                                        this.$Message.warning('退款金额不能大于实际支付金额');
                                        this.refundFlag=true;
                                        return;
                                    }
                                    this.refundFlag=false;
                                    this.charge_dataList[params.index].refundAmt = refundAmt;
                                }
                            }
                        });
                    }
                }],
            charge_dataList: [],
            orderDetails: {},
            baseuser: JSON.parse(Cookies.get('baseUser')),
            exportVisible: false,
            exportData: {
                startTime: '',
                endTime: '',
                status: ''
            },
            invoiceModel: false,
            invoicePath: '',
            classSeasonList:[],
            areaList:[],
            refundFlag:true
        };
    },
    mounted () {
        this.init();
        this.loadList();
        let back = this.$route.params.entry;
        let billId = this.$route.params.billId;
        if (back == 2) { // 直接展示发票窗口
            util.ajax.post('/busine/bill/detail', util.toFormData({// 查询订单详情
                id: billId
            })).then(res => {
                if (res.data.code == 200 && res.data.data != '') {
                    let data = res.data.data;
                    if (data) {
                        // this.invoiceModel = true;
                        this.invoicePath = CONSTANTS.SERVER_HOST + data.invoicePath;
                        let path = this.invoicePath;
                        // let win = window.open(path);
                        let win = window.open();
                        win.focus();
                        win.print();
                    }
                } else {
                    this.$Message.error(res.data.message);
                }
            });
        }
    },
    methods: {
        init () {
            util.ajax.post('/base/datadictionary/findByCode', util.toFormData(
                {CODE: 'CLASS_SEASON'}
            )).then(res => { // 学期数据
                if (res.data.code == 200) {
                    var data = res.data.data;
                    this.classSeasonList = data;
                }
            });
            util.ajax.post('/base/datadictionary/findByCode', util.toFormData(
                {CODE: 'AREA_TYPE'}
            )).then(res => { // 获得区域数据
                if (res.data.code == 200) {
                    var data = res.data.data;
                    this.areaList = data;
                }
            });
        },
        loadList: function () {
            util.ajax.post('/busine/charge/listBySql', util.toFormData({
                page: this.pageIndex,
                size: this.pageSize,
                billCode: this.queryData.billCode,
                studentName: this.queryData.studentName,
                parentPhone: this.queryData.parentPhone,
                className: this.queryData.className,
                status: this.queryData.status,
                areaId: this.queryData.areaId,
                classYear: this.queryData.classYear,
                classSeason: this.queryData.classSeason,
                orgId: this.baseuser.orgId
            })).then(res => {
                this.dataList = res.data.data.list;
                this.total = res.data.data.total;
            });
        },
        refresh () {
            this.queryData = {
                billCode: '',
                studentName: '',
                parentPhone: '',
                className: '',
                status: '',
                areaId: '',
                classYear: '',
                classSeason: ''
            };
            this.init();
            this.loadList();
        },
        getOrderDetails: function () {
            this.orderDetails = {};
            this.charge_dataList = [];
            util.ajax.post('/busine/charge/detailBySql', util.toFormData({
                id: this.billId
            })).then(res => {
                if (res.data.code == 200 && res.data.data != '') {
                    debugger;
                    this.orderDetails = res.data.data;
                    let ord = this.orderDetails;
                    for (let i in ord.charges) {
                        let charge_data = {
                            'id': ord.charges[i].id,
                            'name': ord.charges[i].chargeName,
                            'amt': ord.charges[i].amt,
                            'realAmt': ord.charges[i].realAmt,
                            // 'discountedAmt': ord.charges[i].discountAmt,
                            'discountAmt':0,
                            'refundAmt': ord.charges[i].refundAmt
                        };
                        this.charge_dataList.push(charge_data);
                    }
                    if (ord.sex == 'MAN') {
                        this.orderDetails.sex = '男';
                    } else if (ord.sex == 'WOMAN') {
                        this.orderDetails.sex = '女';
                    }

                    let classSchedules = ord.classSchedules;
                    if (classSchedules) {
                        var text = '';
                        for (let i in classSchedules) {
                            let startTime = classSchedules[i].classStartTime;
                            let endTime = classSchedules[i].classEndTime;
                            if (startTime) {
                                startTime = startTime.substring(0, 2) + ':' + startTime.substring(2, 4);
                            }
                            if (endTime) {
                                endTime = endTime.substring(0, 2) + ':' + endTime.substring(2, 4);
                            }
                            text += util.convertNumToWeekOfDay(classSchedules[i].classType) + ' ' + startTime + '-' + endTime + ' ' + classSchedules[i].classRoomName + '\n';
                        }
                        this.orderDetails.classSchedules = text;
                    }
                }
            });
        },
        showRefund: function (orderid) {
            if (typeof (orderid) === 'number') { // 列上的退费按钮
                util.ajax.post('/busine/charge/detailBySql', util.toFormData({
                    id: this.billId
                })).then(res => {
                    if (res.data.code == 200 && res.data.data != '') {
                        this.orderDetails = res.data.data;
                        let ord = this.orderDetails;
                        for (let i in ord.charges) {
                            let charge_data = {
                                'id': ord.charges[i].id,
                                'name': ord.charges[i].chargeName,
                                'amt': ord.charges[i].amt,
                                'realAmt': ord.charges[i].realAmt,
                                'discountedAmt': ord.charges[i].discountAmt,
                                'discountAmt': 0,
                                'refundAmt': 0
                            };
                            this.charge_dataList.push(charge_data);
                        }
                    }
                });
            } else {
                this.chargeRefundVisable = true;
            }
        },
        doRefund: function (id) {
            this.$Modal.confirm({
                title: '提示',
                content: '确认退款？',
                onOk: () => {
                    util.ajax.post('/busine/charge/doRefund', util.toFormData({
                        data: JSON.stringify(this.charge_dataList)
                    })).then(res => {
                        if (res.data.code == 200 && res.data.data != '') {
                            this.$Message.success(res.data.data);
                            this.chargeRefundVisable = false;
                            this.loadList();
                        } else {
                            this.$Message.error(res.data.message);
                        }
                    });
                },
                onCancel: () => {

                }
            });
        },
        doExport: function () {
            this.$Modal.confirm({
                title: '提示',
                content: '确认导出？',
                onOk: () => {
                    axios({
                        method: 'post',
                        url: CONSTANTS.SERVER_HOST + '/busine/bill/exportDataList',
                        data: util.toFormData(this.exportData),
                        responseType: 'arraybuffer',
                        withCredentials: true
                    }).then(res => {
                        const content = res.data;
                        const blob = new Blob([content], {type: ''});
                        const fileName = '数据表格.xls';
                        if ('download' in document.createElement('a')) { // 非IE下载
                            const elink = document.createElement('a');
                            elink.download = fileName;
                            elink.style.display = 'none';
                            elink.href = URL.createObjectURL(blob);
                            document.body.appendChild(elink);
                            elink.click();
                            URL.revokeObjectURL(elink.href); // 释放URL 对象
                            document.body.removeChild(elink);
                        } else { // IE10+下载
                            navigator.msSaveBlob(blob, fileName);
                        }
                    });
                    // util.ajax.get('/busine/bill/exportDataList', util.toFormData(this.exportData)).then(res => {
                    //
                    //     // if (res.data.code == 200 && res.data.data != '') {
                    //     //     this.$Message.success(res.data.data);
                    //     //     this.chargeRefundVisable = false;
                    //     // } else {
                    //     //     this.$Message.error(res.data.message);
                    //     // }
                    // });
                },
                onCancel: () => {

                }
            });
        },
        invoiceCreate () {

        }
    }
};
